package cn.bxshey.resourceSharing.service.impl;

import cn.bxshey.resourceSharing.dto.login.EnrollDto;
import cn.bxshey.resourceSharing.dto.user.UpdateUserDTO;
import cn.bxshey.resourceSharing.entity.User;
import cn.bxshey.resourceSharing.mapper.UserMapper;
import cn.bxshey.resourceSharing.service.UserService;
import cn.bxshey.resourceSharing.utils.RedisUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-12-16 17:54:45
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    RedisUtils redisUtils;

    @Override
    public String enroll(EnrollDto enrollDto) {
        //如果验证码正确
        Boolean enroll = redisUtils.checkValue(RedisUtils.LOGIN_ENROLL, enrollDto.getEmail(), enrollDto.getCaptcha());
         if(!enroll){
             return null;
         }
        User user = new User();
        BeanUtils.copyProperties(enrollDto,user);
        user.setAuto(UUID.randomUUID().toString());
        String password = BCrypt.hashpw(user.getPassword(),BCrypt.gensalt());
        user.setPassword(password);

        user.setUsername(user.getAuto());
        userMapper.insertUser(user);
        return user.getAuto();
    }

    @Override
    public Integer update(UpdateUserDTO userDTO, Integer uid) {
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        if(!userDTO.getPassword().equals("") && !userDTO.getPassword().equals(" ") ){
            user.setPassword(BCrypt.hashpw(user.getPassword(),BCrypt.gensalt()));
        }
        user.setId(uid);
        return userMapper.update(user);
    }
}

